const express = require("express");
const pool = require("../pool.js");

const scRouter = express.Router();
module.exports = scRouter;
// 查找所有商品分类
scRouter.get("/findAll", (req, res, next) => {
  var page = req.query.page || 1;
  const pagesize = 10;
  var offset = (page - 1) * 10;
  var sql = `select count(scid) as count from supclass`;
  pool.query(sql, (err, r) => {
    if (err) {
      next(err);
      return;
    }
    let pagecount = Math.ceil(r[0].count / pagesize);
    var sql = `select * from supclass limit ?,?`;
    pool.query(sql, [offset, pagesize], (err, r) => {
      if (err) {
        next(err);
        return;
      }
      res.send({ code: 200, data: r, pagecount });
    });
  });
});
// 新建分类
scRouter.post("/insert", (req, res, next) => {
  var scname = req.body.scname;
  var spec = req.body.spec;
  if (scname == "" || scname == undefined || spec == undefined) {
    res.send({ code: 202, msg: "名称不可为空" });
    return;
  }
  var sql = `select sid from supclass where scname=?`;
  pool.query(sql, [scname], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (r.length != 0) {
      res.send({ code: 201, msg: "类名重复" });
    } else {
      sql = `insert into supclass values(null,?,?)`;
      pool.query(sql, [scname, spec], (err, r) => {
        if (err) {
          next(err);
          return;
        }
        res.send({ code: 200, msg: "插入成功" });
      });
    }
  });
});
// 根据类名删除分类
scRouter.delete("/delete", (req, res, next) => {
  var scname = req.query.scname;
  var sql = `delete from supclass where scname=?`;
  pool.query(sql, [scname], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (r.affectedRows != 0) {
      res.send({ code: 200, msg: "删除成功" });
    } else {
      res.send({ code: 201, msg: "删除失败" });
    }
  });
});
